import { IncomingHttpHeaders } from 'http';
import Koa from 'koa';

export class Api {
  private ctx: Koa.Context;

  constructor(ctx: Koa.Context) {
    this.ctx = ctx;
  }

  private res(
    code = 0,
    data: IAnyObject | null,
    msg = '',
    headers?: IncomingHttpHeaders,
  ): void {
    this.ctx.status = 200;

    // 对不同类型进行兼容，感觉可以优化下
    if (headers?.['Content-Type'] === 'text/event-stream') {
      this.ctx.body = data;
      this.ctx.set('Transfer-Encoding', 'chunked');
    } else {
      // 自定义请求头
      this.ctx.body = {
        code,
        msg,
        data,
      };
    }

    // content-type要最后设置
    this.ctx.set(
      'Content-Type',
      headers?.['Content-Type'] || 'application/json'
    );
  }

  success(data: IAnyObject, msg = '', headers?: IncomingHttpHeaders): void {
    return this.res(0, data, msg, headers);
  }

  fail(code = -1, msg = '', headers?: IncomingHttpHeaders): void {
    return this.res(code, null, msg, headers);
  }
}

export default function apiMiddleare(): Koa.Middleware<
  Koa.DefaultState,
  Koa.DefaultContext
> {
  return async (ctx: Context, next: Next): Promise<void> => {
    ctx.api = new Api(ctx);
    return next();
  };
}
